<script setup lang="ts">
// import validate from "_s/common/validate";
import ThemeSwitch from "_c/ThemeSwitch/index.vue";
import i18n from "_c/i18n/index.vue";
import { userLogin } from "_s/config/user";
import common from "_s/common/localstore";
import { encrypt } from "_s/common/crypto";
import { QForm } from "quasar";
const router = useRouter();
const { t } = useI18n();
const { notify, dark, loading } = useQuasar();
const form = ref({
  username: "admin",
  password: "123123"
});

const formRef = useTemplateRef("formRef") as Ref<InstanceType<typeof QForm>>;

const submit = async () => {
  loading.show();
  const { code, data, msg } = await userLogin({
    username: form.value.username,
    password: encrypt(form.value.password)
  });
  loading.hide();
  if (code == 0) {
    notify({
      type: "success",
      message: "登录成功"
    });

    common.setToken("Bearer " + data);
    void router.push({
      path: "/"
    });
  } else {
    notify({
      type: "error",
      message: msg
    });
  }
};

const formRules = {
  username: [(val: string) => (val != null && val !== "") || t("login.rules.username")],
  password: [(val: string) => (val != null && val !== "") || t("login.rules.password"), (val: string) => val.length >= 6 || t("login.rules.passwordLength")]
};
</script>

<template>
  <q-page>
    <div class="changeBtn">
      <i18n></i18n>
      <ThemeSwitch class="q-mx-sm"></ThemeSwitch>
    </div>

    <div
      class="row items-center justify-center"
      style="height: calc(100vh - 32px)"
    >
      <q-card
        class="my-card q-pa-lg"
        flat
        bordered
      >
        <q-card-section>
          <div class="title">Login</div>
          <q-form
            ref="formRef"
            @keyup.enter.prevent="submit"
            autocomplete="off"
          >
            <q-input
              ref="username"
              v-model="form.username"
              class="input q-mt-sm"
              dense
              :label="$t('login.username')"
              lazy-rules
              :rules="formRules.username"
            />
            <q-input
              ref="password"
              v-model="form.password"
              type="password"
              dense
              class="input"
              :label="$t('login.password')"
              lazy-rules
              :rules="formRules.password"
            />
            <q-btn
              class="input"
              unelevated
              :outline="dark.isActive"
              color="primary"
              :label="$t('pub.submit')"
              @click.prevent="submit"
            />
          </q-form>
        </q-card-section>
      </q-card>
    </div>
  </q-page>
</template>

<style lang="scss" scoped>
.changeBtn {
  position: fixed;
  top: 5%;
  right: 5%;
}

.input {
  width: 320px;
}

.title {
  font-size: 3em;
  color: var(--q-primary);
}

.q-btn {
  text-transform: none;
}
</style>
